package com.rxy.socketdemo

import org.junit.Test

import org.junit.Assert.*
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.PrintWriter
import java.net.ServerSocket
import java.net.Socket

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * See [testing documentation](http://d.android.com/tools/testing).
 */
class ExampleUnitTest {
    @Test
    fun addition_isCorrect() {
        assertEquals(4, 2 + 2)
    }

    @Test
    fun testSocketService() {
        val PORT = 8888
        try {
            ServerSocket(PORT).use { serverSocket ->
                println("服务器启动，监听端口: $PORT")
                while (true) {
                    // 等待客户端连接
                    val clientSocket = serverSocket.accept()

                    // 获取输入输出流
                    try {
                        clientSocket.use {
                            BufferedReader(
                                InputStreamReader(clientSocket.getInputStream())
                            ).use { `in` ->
                                PrintWriter(
                                    clientSocket.getOutputStream(), true
                                ).use { out ->
                                    println("客户端连接: " + clientSocket.inetAddress + ":" + clientSocket.port)
                                    var inputLine: String
                                    // 读取客户端发送的消息
                                    while ((`in`.readLine().also { inputLine = it }) != null) {
                                        println("收到客户端消息: $inputLine")

                                        // 处理消息并返回响应
                                        val response = "服务器已收到: $inputLine"
                                        out.println(response)

                                        // 简单退出条件
                                        if ("exit".equals(inputLine, ignoreCase = true)) {
                                            break
                                        }
                                    }
                                }
                            }
                        }
                    } catch (e: IOException) {
                        System.err.println("客户端通信异常: " + e.message)
                    } finally {
                        println("客户端断开连接")
                    }
                }
            }
        } catch (e: IOException) {
            System.err.println("服务器异常: " + e.message)
        }

    }
}